let commonFunction = {

	/**
	 * 加载头部样式
	 */
	loadHeader: function() {
		layui.use(['element', 'laydate', 'upload'], function() {
			let element = layui.element;
			let laydate = layui.laydate;
			let upload = layui.upload;
			let form = layui.form;
			element.init();
			element.on('tab(bar)', function(data) {
				console.log(data);
			});
			laydate.render({
				elem: '#time',
				type: 'datetime',
				range: ['#startTime', '#endTime']
			});
			//拖拽上传
			upload.render({
				elem: '#uploadFile',
				accept: 'file',
				url: '/tp-view/logging/parseMonitor',
                before: function () {
					// 清除数据
                    localStorage.removeItem("poolData");
                    sessionStorage.removeItem("DTP_time");
                    sessionStorage.removeItem("dtp_data");
                    sessionStorage.removeItem("poolNames");
				},
				done: function(data) {
                    var index = layer.load(1, {
                        shade: [0.2, '#ddd']
                    });
                    let formData = form.val('logging-file-form');
                    if (data.code == 200) {
                        data = data.data;
                        loadLoggingData(data);
                        // 渲染select
                        $("select[name=poolName]").empty();
                        let poolNames = JSON.parse(sessionStorage.getItem("poolNames"));
                        if (poolNames != null && poolNames != undefined) {
                            $.each(poolNames, function(index, element) {
                                if (index == 0) {
                                    formData.poolName = element;
                                }
                                sessionStorage.setItem("dtp_data", JSON.stringify(formData));
                                $("select[name=poolName]").append(
                                    "<option value='" + element + "'>" +
                                    element + "</option>");
                            });
                            form.render();
                        }
                        // load echarts
                        loadLoggingEchart("echart", option);
                        layer.close(index);
                    } else {
                        errorLayer("接口请求异常（/tp-view/logging/parseMonitor）info:" + data.msg);
                    }
				}
			});
		});
	},

	/**
	 * 加载表单提交数据
	 */
	loadSubmit: function() {
		layui.use(['form', 'layer'], function() {
			let form = layui.form;
			let layer = layui.layer;
			let laydate = layui.laydate;
			$ = layui.$;

			$("#search").on("click", function() {
				var index = layer.load(1, {
					shade: [0.2, '#ddd']
				});
				let formData = form.val('form');
				let url = formData.url;
				let time = formData.time;
				if (isCheck(formData)) {
					localStorage.removeItem("poolData");
					sessionStorage.removeItem("DTP_time");
					sessionStorage.removeItem("poolNames");
				}
				startGetUrlByTime(url, time);


				let dtpData = sessionStorage.getItem("dtp_data");
				if (dtpData != null && dtpData != undefined) {
					dtpData = JSON.parse(dtpData);
					if (dtpData.poolName != "") {
						sessionStorage.setItem("dtp_data", JSON.stringify(formData));
						layer.close(index);
					} else {
						var tmpInterval = setInterval(function() {
							$("select[name=poolName]").empty();
							let poolNames = JSON.parse(sessionStorage.getItem(
								"poolNames"));
							if (poolNames != null && poolNames != undefined) {
								$.each(poolNames, function(index, element) {
									if (index == 0) {
										formData.poolName = element;
										sessionStorage.setItem("dtp_data", JSON
											.stringify(formData));
										loadPoolData("echart", option);
									}
									$("select[name=poolName]").append(
										"<option value='" + element + "'>" +
										element + "</option>");
								});
								form.render();
								layer.close(index);
								clearInterval(tmpInterval);
							}
						}, 100);
					}
				} else {
					var tmpInterval = setInterval(function() {
						$("select[name=poolName]").empty();
						let poolNames = JSON.parse(sessionStorage.getItem("poolNames"));
						if (poolNames != null && poolNames != undefined) {
							$.each(poolNames, function(index, element) {
								if (index == 0) {
									formData.poolName = element;
									sessionStorage.setItem("dtp_data", JSON
										.stringify(formData));
									loadPoolData("echart", option);
								}
								$("select[name=poolName]").append(
									"<option value='" + element + "'>" +
									element + "</option>");
							});
							form.render();
							layer.close(index);
							clearInterval(tmpInterval);
						}
					}, 100);
				}
				return false;
			});

			$(".clear").on("click", function() {
				if (dataSaveInterval != undefined && dataSaveInterval != null) {
					clearInterval(dataSaveInterval);
				}

				if (loadDataInterval != undefined && loadDataInterval != null) {
					clearInterval(loadDataInterval);
				}
				localStorage.removeItem("poolData");
				sessionStorage.removeItem("DTP_time");
				sessionStorage.removeItem("dtp_data");
				sessionStorage.removeItem("poolNames");
				return false;
			});

			$("#parse").on("click", function() {
				var index = layer.load(1, {
					shade: [0.2, '#ddd']
				});
				let formData = form.val('logging-form');
				if (isLoggingCheck(formData)) {
                    localStorage.removeItem("poolData");
                    sessionStorage.removeItem("DTP_time");
                    sessionStorage.removeItem("poolNames");

                    $.ajax({
                        type: "POST",
                        url: "/tp-view/logging/view",
                        contentType: "application/json",
                        data: JSON.stringify(formData),
                        success: function(data) {
                            if (data.code == 200) {
                                data = data.data;
                                loadLoggingData(data);
                                // 渲染select
                                $("select[name=poolName]").empty();
                                let poolNames = JSON.parse(sessionStorage.getItem("poolNames"));
                                if (poolNames != null && poolNames != undefined) {
                                    $.each(poolNames, function(index, element) {
                                        if (index == 0) {
                                            formData.poolName = element;
                                        }
                                        sessionStorage.setItem("dtp_data", JSON.stringify(formData));
                                        $("select[name=poolName]").append(
                                            "<option value='" + element + "'>" +
                                            element + "</option>");
                                    });
                                    form.render();
                                }
                                // load echarts
                                loadLoggingEchart("echart", option);
                                layer.close(index);
                            } else {
                                errorLayer("接口请求异常（/tp-view/logging/view）info:" + data.msg);
                            }
                        },
                        error: function(e) {
                            errorLayer("接口请求异常（/tp-view/logging/view）");
                            console.log(e);
                            layer.close(index);
                        }
                    });
				} else {
                    sessionStorage.setItem("dtp_data", JSON.stringify(formData));
                    // load echarts
                    loadLoggingEchart("echart", option);
                    layer.close(index);
				}
				return false;
			});

			$("#change").on("click", function() {
                let formData = form.val('logging-file-form');
				if (localStorage.getItem("poolData") == null) {
                    errorLayer("请先上传文件");
				} else {
                    sessionStorage.setItem("dtp_data", JSON.stringify(formData));
                    // load echarts
                    loadLoggingEchart("echart", option);
				}
				return false;
			});
		});
	},

	loadEchart: function(id, option) {
		var charts = echarts.init(document.getElementById(id));
		charts.setOption(option);
	}
}

let $;
// 存储数据定时器
let dataSaveInterval;
// 读取数据定时器
let loadDataInterval;

/**
 * 日志线程池数据
 * @param {Object} data
 */
function loadLoggingData(data) {
	var names = new Array();
	var poolData = {};
	$.each(data.data, function(index, element) {
		if (element["poolName"] != undefined) {
			var poolName = element["poolName"];
			if (poolData[poolName] == undefined || poolData[poolName] == null) {
				poolData[poolName] = {};
			}
			// 数据装换
			let arrayKey = new Array();
			for (key in poolObject) {
				arrayKey.push(key);
			}
			$.each(arrayKey, function(index, key) {
				if (poolData[poolName][key] == undefined || poolData[poolName][key] == null) {
					poolData[poolName][key] = new Array();
				}
				poolData[poolName][key].push(element[key]);
			});
	
		}
	});
	for (var key in poolData) {
		names.push(key);
	}
	// 存于线程池数据
	sessionStorage.setItem("poolNames", JSON.stringify(names));
	localStorage.setItem("poolData", JSON.stringify(poolData));
	// 设置时间
	sessionStorage.setItem("DTP_time", JSON.stringify(data.timeList));
}

/**
 * 渲染日志echart图
 */
function loadLoggingEchart(id, option) {
    // 写入x轴数据
    option.xAxis.data = JSON.parse(sessionStorage.getItem("DTP_time"));
    //写入折线图
    let arrayKey = new Array();
    let arrayValue = new Array();
    for (key in poolObject) {
        arrayKey.push(key);
        arrayValue.push(poolObject[key]);
    }
    option.legend.data = arrayValue;
    let formData = JSON.parse(sessionStorage.getItem("dtp_data"));
    let poolData = JSON.parse(localStorage.getItem("poolData"));
    let poolName = formData.poolName;
    let data = poolData[poolName];
    // 数据转化
    for (var i = 0; i < arrayKey.length; i++) {
        option.series[i] = {
            name: arrayValue[i],
            data: data[arrayKey[i]],
            type: 'line',
            smooth: true
        }
    }

    var charts = echarts.init(document.getElementById(id));
    charts.setOption(option);
}

/**
 * 加缓存数据
 */
function loadPoolData(id, option) {
	let time = JSON.parse(sessionStorage.getItem("dtp_data"))["time"];
	if (loadDataInterval != undefined) {
		clearInterval(loadDataInterval);
	}
	loadDataInterval = setInterval(function() {
		// 写入x轴数据
		option.xAxis.data = JSON.parse(sessionStorage.getItem("DTP_time"));
		//写入折线图
		let arrayKey = new Array();
		let arrayValue = new Array();
		for (key in poolObject) {
			arrayKey.push(key);
			arrayValue.push(poolObject[key]);
		}
		option.legend.data = arrayValue;
		let formData = JSON.parse(sessionStorage.getItem("dtp_data"));
		let poolData = JSON.parse(localStorage.getItem("poolData"));
		let poolName = formData.poolName;
		let data = poolData[poolName];
		// 数据转化
		for (var i = 0; i < arrayKey.length; i++) {
			option.series[i] = {
				name: arrayValue[i],
				data: data[arrayKey[i]],
				type: 'line',
				smooth: true
			}
		}

		var charts = echarts.init(document.getElementById(id));
		charts.setOption(option);
	}, time * 1000);
}

/**
 * logging是否校验通过
 */
function isLoggingCheck(data) {
    let dtpData = sessionStorage.getItem("dtp_data");
    if (dtpData == undefined || dtpData == null) {
        return true;
    }
    dtpData = JSON.parse(dtpData);
    if (data.path == dtpData.path && data.endTime == dtpData.endTime && data.limit == dtpData.limit && data.startTime == dtpData.startTime) {
        return false;
    } else {
        return true;
    }
}

/**
 * endpoint是否校验通过
 */
function isCheck(data) {
	let dtpData = sessionStorage.getItem("dtp_data");
	if (dtpData == undefined || dtpData == null) {
		return false;
	}
	dtpData = JSON.parse(dtpData);
	if (data.url == dtpData.url && data.time == dtpData.time) {
		return false;
	} else {
		return true;
	}
}

/**
 * 开启定时器
 * @param {Object} url
 * @param {Object} time
 */
function startGetUrlByTime(url, time) {
	if (dataSaveInterval != undefined) {
		clearInterval(dataSaveInterval);
	}
	loadUrl(url);
	dataSaveInterval = setInterval(function() {
		loadUrl(url);
	}, time * 1000);
}

/**
 * 加载数据
 * @param {Object} url
 */
function loadUrl(url) {
	let data = {
		"url": url
	};
	$.ajax({
		type: "POST",
		url: "/tp-view/endpoint/view",
		contentType: "application/json",
		data: JSON.stringify(data),
		dataType: "json",
		success: function(data) {
			if (data.code == 200) {
				data = JSON.parse(data.data);

				var names = new Array();
				let poolData = localStorage.getItem("poolData");
				if (poolData == null || poolData == undefined) {
					poolData = new Object();
				} else {
					poolData = JSON.parse(poolData);
				}
				$.each(data, function(index, element) {
					if (element["poolName"] != undefined) {
						var poolName = element["poolName"];
						names.push(poolName);
						if (poolData[poolName] == undefined || poolData[poolName] == null) {
							poolData[poolName] = {};
						}
						// 数据装换
						let arrayKey = new Array();
						for (key in poolObject) {
							arrayKey.push(key);
						}
						$.each(arrayKey, function(index, key) {
							if (poolData[poolName][key] == undefined || poolData[poolName][
									key
								] == null) {
								poolData[poolName][key] = new Array();
							}
							poolData[poolName][key].push(element[key]);
						});

					}
				});
				// 存于线程池数据
				sessionStorage.setItem("poolNames", JSON.stringify(names));
				localStorage.setItem("poolData", JSON.stringify(poolData));

				// 设置开始时间
				setTimeArray();
			} else {
				errorLayer("接口请求异常（" + url + "）异常信息：" + data.msg);
			}
		},
		error: function(e) {
			errorLayer("接口请求异常（" + url + "）");
			console.log(e);
		}
	});
}

/**
 * 异常弹窗信息
 * @param {Object} msg
 */
function errorLayer(msg) {
	layui.use(['layer'], function() {
		let layer = layui.layer;
		layer.msg(msg, {
			icon: 2,
			time: 2000
		});
	});
}

/**
 * 获取到时间的间隔
 * @param {Object} startTime
 */
function setTimeArray() {
	let date = new Date();
	let hour = date.getHours();
	let minute = date.getMinutes();
	let seconds = date.getSeconds();
	let dateArray = sessionStorage.getItem("DTP_time");
	if (dateArray == undefined || dateArray == null) {
		dateArray = new Array();
		dateArray.push(hour + ":" + minute + ":" + seconds);
		sessionStorage.setItem("DTP_time", JSON.stringify(dateArray));
	} else {
		dateArray = JSON.parse(dateArray);
		dateArray.push(hour + ":" + minute + ":" + seconds);
		sessionStorage.setItem("DTP_time", JSON.stringify(dateArray));
	}

}
